package com.rfsp.mcp.controller.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rfsp.common.base.ResultVO;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.FileUtil;
import com.rfsp.common.util.JsonUtil;
import com.rfsp.common.util.StringUtil;
import com.rfsp.mcp.mapper.FinanceMiInfoMapper;
import com.rfsp.mcp.pojo.po.FinanceMiInfoPO;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.common.service.AreaService;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.mcp.pojo.po.PunishPO;
import com.rfsp.mcp.pojo.vo.FinanceVO;
import com.rfsp.mcp.pojo.vo.HospitalPdfVO;
import com.rfsp.mcp.pojo.vo.HospitalVO;
import com.rfsp.mcp.pojo.vo.PfmVO;
import com.rfsp.mcp.service.FinanceService;
import com.rfsp.mcp.util.McpPdfUtil;
import com.rfsp.mcp.service.OrgYbjService;
import com.rfsp.mcp.service.PfmService;

import tk.mybatis.mapper.entity.Example;

@Controller("BaseHospitalController")
@RequestMapping("/base/hospital")
public class BaseHospitalController extends BaseController{

    public Logger logger = LoggerFactory.getLogger(BaseHospitalController.class);

    @Value("${mcp.file-temp-path-hospital}")
    private String hospitalPdfPath;

    @Autowired
    private OrgYbjService orgYbjService;
    
    @Autowired
    FinanceService financeService;
    
    @Autowired
    PfmService pfmService;
    
    @Autowired
    FinanceMiInfoMapper financeMiInfoMapper;
    
    @Autowired
	public AreaService areaService;
    
    @GetMapping("/detail")
    public String detail(ModelMap model, Long id ,String aid) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.detail"));
        
        logger.info("XXXXXXXXXXXXX");
        
        ResultVO<HospitalVO> vo = ResultVO.success(new HospitalVO());
        model.put("vo", vo);
        
        OrgPO currentOrg = ShiroUtils.getCurrentOrg();

        HospitalPdfVO pdfVO = orgYbjService.getHospitalPdfVO(id, aid);
        pdfVO.setOrgCatalog(currentOrg.getOrgCatalog());
        model.put("vo",pdfVO);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BaseHospitalController.detail"));
        return "base/hospital/detail";
    }

    @GetMapping("/detail1")
    public String detail1(ModelMap model,Long id ,String aid) throws JsonProcessingException {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.detail1"));
        String pdfPath = "/mcp/base/hospital/pdf/";

        logger.info("ZZZZZZZZZZZZZ");
        
        
        PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
        if(pfm != null) {
        	if(!"0".equals(pfm.getItfType()))
                pdfPath = "/mcp/base/hospital/pdfYBD/";
        }
        

        if(id == null && aid == null) {//取得当前机构的主体信息
            model.put("pdfPath", pdfPath);
        }else {//根据id，aid取得主体信息
        	model.put("pdfPath",pdfPath+"?id="+id+"&aid="+aid);
        }
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BaseHospitalController.detail1"));
        return "base/hospital/detail1";
    }



    @GetMapping("/pdf")
    public void pdf(ModelMap model, Long id,String aid,HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.pdf"));
        ResultVO<HospitalVO> vo = ResultVO.success(new HospitalVO());
        
        if(id == null && aid == null) {
        	//OrgPO currentOrg = ShiroUtils.getCurrentOrg();
            //PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
        	//OrgYbjPO orgYbjPO = orgYbjService.getYbjId(currentOrg.getId(), pfm.getId());
            OrgYbjPO orgYbjPO = ShiroUtils.getAttribute("org_ybj");
            id = orgYbjPO.getId();
            aid = orgYbjPO.getAid();
        }
        
        Map<String,Object> dataMap = orgYbjService.getHospitalPdfMap(id, aid);
        String dirPath = FileUtil.getRootPath(hospitalPdfPath).replaceFirst("date", StringUtil.dateToString(new Date(), "yyyy/MM/dd"));
        
        try {
        	dirPath = McpPdfUtil.buildMiInfoPDF(dataMap, dirPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        logger.info("生成预览文件成功");
        request.getSession().setAttribute(id+"orgPdfPath",dirPath);
        File file = new File(dirPath);
        FileInputStream fileInputStream = new FileInputStream(file);
        response.setHeader("Content-Type", "application/pdf");
        OutputStream outputStream = response.getOutputStream();
        IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BaseHospitalController.pdf"));
    }

    @GetMapping("/pdfYBD")
    public void pdfYBD(ModelMap model, Long id,String aid, HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.pdfYBD"));
        ResultVO<HospitalVO> vo = ResultVO.success(new HospitalVO());

        
        logger.info("request id="+id+", aid="+aid);
        
        if(id == null && aid == null) {
            //OrgPO currentOrg = ShiroUtils.getCurrentOrg();
            //PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
            //OrgYbjPO orgYbjPO = orgYbjService.getYbjId(currentOrg.getId(), pfm.getId());
            OrgYbjPO orgYbjPO = ShiroUtils.getAttribute("org_ybj");
            id = orgYbjPO.getId();
            aid = orgYbjPO.getAid();
        }
        
        logger.info("shiro id="+id+", aid="+aid);

        Map<String,Object> dataMap = orgYbjService.getHospitalYBDPdfMap(id, aid);
        String dirPath = FileUtil.getRootPath(hospitalPdfPath).replaceFirst("date", StringUtil.dateToString(new Date(), "yyyy/MM/dd"));

        try {
            dirPath = McpPdfUtil.buildMiInfoYBDPDF(dataMap, dirPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        logger.info("生成预览文件成功");
        request.getSession().setAttribute(id+"orgPdfPath",dirPath);
        File file = new File(dirPath);
        FileInputStream fileInputStream = new FileInputStream(file);
        response.setHeader("Content-Type", "application/pdf");
        OutputStream outputStream = response.getOutputStream();
        IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BaseHospitalController.pdfYBD"));
    }

    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response, ModelMap model,Long id, String aid) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {

        OrgYbjPO ybjPO = orgYbjService.getOrgYbj(id,aid);
        String dirPath = (String) request.getSession().getAttribute(id+"orgPdfPath");
        try {
            FileUtil.downloadfile(request, response, dirPath, ybjPO.getOrgCode()+".pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    
    
    @RequestMapping("/downloadPDF")
    public String downloadPDF(HttpServletRequest request, HttpServletResponse response, ModelMap model,Long id, String aid) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {

    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.pdf"));
        ResultVO<HospitalVO> vo = ResultVO.success(new HospitalVO());
        
        OrgPO currentOrg = ShiroUtils.getCurrentOrg();
        
        PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
        String itf_type = pfm.getItfType();  //0：宿迁；1：抚顺；2江浙；9其他
        
        if(id == null && aid == null) {
          	//OrgYbjPO orgYbjPO = orgYbjService.getYbjId(currentOrg.getId(), pfm.getId());
            OrgYbjPO orgYbjPO = ShiroUtils.getAttribute("org_ybj");
              id = orgYbjPO.getId();
              aid = orgYbjPO.getAid();
          }
        
        String dirPath = FileUtil.getRootPath(hospitalPdfPath).replaceFirst("date", StringUtil.dateToString(new Date(), "yyyy/MM/dd"));
        
        try {
	        if(itf_type .equals("0")) { 
	              Map<String,Object> dataMap = orgYbjService.getHospitalPdfMap(id, aid);
	              dirPath = McpPdfUtil.buildMiInfoPDF(dataMap, dirPath);
	      		
	        }else if(itf_type.equals("1")) {
	        	 Map<String,Object> dataMap = orgYbjService.getHospitalYBDPdfMap(id, aid);
	        	dirPath = McpPdfUtil.buildMiInfoYBDPDF(dataMap, dirPath);
	        }
	        
	        logger.info("生成预览文件成功");
	        FileUtil.downloadfile(request, response, dirPath, currentOrg.getOrgCode()+".pdf");
	        
        } catch (Exception e) {
  			e.printStackTrace();
  		}

        return null;
    }


    
    
    //-----------------------------------------------------------------------
    
    

    /*
     * 资金方融资申请列表，点击两定机构，展示PDF，需要取得创建融资申请时，存在mi表中的json数据，进行生成
     */
    @GetMapping("/detail4Finance")
    public String detail4Finance(ModelMap model,Long id ,String aid) throws JsonProcessingException {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.detail4Finance"));
        String pdfPath = "/mcp/base/hospital/pdf4Finance";
        model.put("pdfPath",pdfPath+"?id="+id+"&aid="+aid);
        model.put("id", id);
        model.put("aid", aid);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BaseHospitalController.detail4Finance"));
        return "base/hospital/detail4Finance";
    }
    
    /**
     * 根据融资申请2id，查询两顶机构pdf
     * @param model
     * @param id 融资申请id
     * @param aid 融资申请aid
     * @param request
     * @param response
     * @throws IOException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @GetMapping("/pdf4Finance")
    public void pdf4Finance(ModelMap model, Long id,String aid,HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    	 logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BaseHospitalController.pdf4Finance"));
    	 logger.info("financeId="+id);
    	 
    	 //先确定融资申请是的PFM
    	 FinanceVO financeVO = financeService.getBy2Id(id, aid);
    	 PfmVO pfmVO = pfmService.getById(financeVO.getPfmId());
    	 String itfType = pfmVO.getItfType();
    	 
    	 //再拼装数据
    	 Map<String,Object> dataMap = null;
    	 
         Example example = new Example(FinanceMiInfoPO.class);
         example.createCriteria().andEqualTo("financeId", id);
         List<FinanceMiInfoPO> miPOList = financeMiInfoMapper.selectByExample(example);
         if(miPOList != null && !miPOList.isEmpty()) {
        	 FinanceMiInfoPO miPO = miPOList.get(0);
        	 String miInfoJson = miPO.getMiInfo();
        	 logger.info("miInfoJson="+miInfoJson);
        	 
        	 dataMap = JsonUtil.toMap2(miPO.getMiInfo());
        	 
        	 String fullAddress = areaService.getFullAddress(String.valueOf(dataMap.get("bizArea")));
        	 dataMap.put("bizArea", fullAddress);
        	 
        	 if("1".equals(String.valueOf(dataMap.get("punishDataFlag")))) {
        		 List<Map<String,String>> list = (List<Map<String,String>>)dataMap.get("punishList");
        		 List<PunishPO> punishiPOList = new ArrayList<PunishPO>();
        		 
        		 if(list != null && !list.isEmpty()) {
        			 for(Map<String,String> map:list) {
        				 PunishPO punishPO = new PunishPO();
                		 punishPO.setOrgName(map.get("orgName"));
                		 punishPO.setDocumentNo(map.get("documentNo"));
                		 punishPO.setErrorInfo(map.get("errorInfo"));
                		 punishPO.setPunishType(map.get("punishType"));
                		 punishPO.setPunishInfo(map.get("punishInfo"));
                		 punishPO.setPunishAmount(map.get("punishAmount"));
                		 punishPO.setRevokeOrgInfo(map.get("revokeOrgInfo"));
                		 punishPO.setPunishStartDate(map.get("punishStartDate"));
                		 punishPO.setPunishEndDate(map.get("punishEndDate"));
                		 
                		 punishiPOList.add(punishPO);
        			 }
        		 }
        		 
        		 dataMap.put("punishList", punishiPOList);
        	 }
         }
         
         String dirPath = FileUtil.getRootPath(hospitalPdfPath).replaceFirst("date", StringUtil.dateToString(new Date(), "yyyy/MM/dd"));
         
         //生成pdf
         try {
        	 if("0".equals(itfType)) {
        		 dirPath = McpPdfUtil.buildMiInfoPDF(dataMap, dirPath);
        	 }else {
        		 dirPath = McpPdfUtil.buildMiInfoYBDPDF(dataMap, dirPath);
        	 }
 		 } catch (Exception e) {
 			e.printStackTrace();
 		 }
         
         logger.info("生成预览文件成功");
         request.getSession().setAttribute(id+"orgPdfPath",dirPath);
         File file = new File(dirPath);
         FileInputStream fileInputStream = new FileInputStream(file);
         response.setHeader("Content-Type", "application/pdf");
         //URLEncoder.encode("主体信息汇总表.pdf","UTF-8")
         response.setHeader("Content-Disposition", "filename="+String.valueOf(dataMap.get("orgCode"))+".pdf");
         OutputStream outputStream = response.getOutputStream();
         IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
         logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BaseHospitalController.pdf4Finance"));
    }
    
    
    @RequestMapping("/download4Finance")
    public String download4Finance(HttpServletRequest request, HttpServletResponse response, ModelMap model,Long id, String aid) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {

    	String fileName = "";
    	
    	Example example = new Example(FinanceMiInfoPO.class);
        example.createCriteria().andEqualTo("financeId", id);
        List<FinanceMiInfoPO> miPOList = financeMiInfoMapper.selectByExample(example);
        if(miPOList != null && !miPOList.isEmpty()) {
        	FinanceMiInfoPO miPO = miPOList.get(0);
        	String miInfoJson = miPO.getMiInfo();
       	 	logger.info("miInfoJson="+miInfoJson);
       	 
       	 	Map<String,Object> dataMap = JsonUtil.toMap2(miPO.getMiInfo());
       	 	fileName = String.valueOf(dataMap.get("orgCode"));
        }
    	
        String dirPath = (String) request.getSession().getAttribute(id+"orgPdfPath");
        try {
            FileUtil.downloadfile(request, response, dirPath, fileName + ".pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
